package org.example.lock;

import java.util.concurrent.locks.StampedLock;

public class StampedLockExample {

    private final StampedLock lock = new StampedLock();
    private double x;
    private double y;

    // 获取读锁
    public double distance() {
        long stamp = lock.readLock(); // 获取读锁
        try {
            return Math.sqrt(x * x + y * y);
        } finally {
            lock.unlockRead(stamp); // 释放读锁
        }
    }

    // 获取写锁
    public void move(double deltaX, double deltaY) {
        long stamp = lock.writeLock(); // 获取写锁
        try {
            x += deltaX;
            y += deltaY;
        } finally {
            lock.unlockWrite(stamp); // 释放写锁
        }
    }

    // 乐观读锁尝试
    public double optimisticDistance() {
        long stamp = lock.tryOptimisticRead(); // 尝试获取乐观读锁
        double currentX = x;
        double currentY = y;
        if (!lock.validate(stamp)) { // 检查锁的有效性
            stamp = lock.readLock(); // 获取读锁
            try {
                currentX = x;
                currentY = y;
            } finally {
                lock.unlockRead(stamp); // 释放读锁
            }
        }
        return Math.sqrt(currentX * currentX + currentY * currentY);
    }

    public static void main(String[] args) {
        StampedLockExample example = new StampedLockExample();
        example.move(10, 20);
        System.out.println("Distance: " + example.distance());
        System.out.println("Optimistic Distance: " + example.optimisticDistance());
    }
}